<?php

namespace App\Http\Controllers\Review;

use App\Http\Controllers\Controller;
use App\Models\Review\ActivityFormModel;
use App\Models\Review\ActivityModel;
use Exception;
use Illuminate\Http\Request;
use MongoDB\Client;
use xmltool\Xml2Object;

class ActivityController extends Controller{
    public function actMake(Request $request){
        $file="test.xml";
        return sprintf("<pre>%s</pre>",ActivityModel::makeFromXml($file));
    }
    public function actDoit(Request $request){
        $cmd=$request['cmd']??null;
        if(empty($cmd)){
            throw new Exception("cmd is null");
        }
        $data=[
            "success"=>false,
            "msg"=>"error",
            "data"=>null
        ];
        switch($cmd){
            case 'insert':{
                $params=[
                    "uni_id"=>"activity_".uniqid()."_".time(),
                    "user_id"=>$request['login_user_id']??1,
                    "title"=>$request['title'],
                    "intro"=>$request['intro'],
                    "scope"=>$request['scope']
                ];
                $obj=ActivityModel::create($params);
                if(empty($obj)){
                    $data['msg']='Error:create activity model';
                }else{
                    $data['msg']='ok';
                    $data['success']=true;
                    $data['data']=$obj->toArray();
                }
                break;
            }
            case 'update':{
                $id=$request['id']??null;
                if(empty($id)){
                    throw new Exception("update.id is null");
                }
                $id_type=$request['id_type']??'id';
                $where=[$id_type=>$id];
                $params=[
                    "title"=>$request['title'],
                    "intro"=>$request['intro'],
                    "scope"=>$request['scope']
                ];
                $v=ActivityModel::where($where)->update($params);
                $data['msg']=empty($v)?'fail':'ok';
                $data['success']=empty($v)?false:true;
                break;
            }
            case 'delete':{
                $id=$request['id']??null;
                if(empty($id)){
                    throw new Exception("update.id is null");
                }
                $id_type=$request['id_type']??'id';
                $where=[$id_type=>$id];
                $v=ActivityModel::where($where)->update([
                    'status'=>'DISABLED'
                ]);
                $data['msg']=empty($v)?'fail':'ok';
                $data['success']=empty($v)?false:true;
                break;
            }
            case 'create_form':{
                $activity_id_type=$request['activity_id_type']??'id';
                $activity_id=$request['activity_id']??null;
                if(empty($activity_id)){
                    throw new Exception('Error:no activity.id');
                }
                $fields=$request->json();
                $fields=$fields->all();
                unset($fields['cmd']);//去除cmd JSON Key
                unset($fields['uni_id']);//去除cmd JSON Key
                unset($fields['user_id']);//去除cmd JSON Key
                unset($fields['created_at']);//去除cmd JSON Key
                unset($fields['created_at_str']);//去除cmd JSON Key
                unset($fields['activity_id']);//去除cmd JSON Key
                unset($fields['activity_id_type']);//去除cmd JSON Key
                $uni_id="form_".uniqid()."_".time();
                $params=[
                    'activity_id_type'=>$activity_id_type,
                    'uni_id'=>$uni_id,
                    "user_id"=>$request['login_user_id']??1,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                    'created_at_str'=>date('Y-m-d H:i:s'),
                    'updated_at_str'=>date('Y-m-d H:i:s')
                ];
                foreach($fields as $k=>$v){
                    $params[$k]=$v;
                }
                $client=new Client(env("MONGO_URI"));
                $database=$client->selectDatabase("review");
                $collection=$database->selectCollection("forms");
                $v=$collection->insertOne($params);
                $id=$v->getInsertedId();
                $data['msg']='ok';
                $data['success']=true;
                $data['data']=$v;
                break;
            }
            case 'update_form':{
                $uni_id=$request['uni_id']??null;
                if(empty($uni_id)){
                    throw new Exception('Error:no activity.form.uni_id');
                }
                $fields=$request->json();
                $fields=$fields->all();
                unset($fields['cmd']);//去除cmd JSON Key
                unset($fields['uni_id']);//去除cmd JSON Key
                unset($fields['user_id']);//去除cmd JSON Key
                unset($fields['created_at']);//去除cmd JSON Key
                unset($fields['created_at_str']);//去除cmd JSON Key
                unset($fields['activity_id']);//去除cmd JSON Key
                unset($fields['activity_id_type']);//去除cmd JSON Key
                $params=[
                    'updated_at'=>time(),
                    'updated_at_str'=>date('Y-m-d H:i:s')
                ];
                foreach($fields as $k=>$v){
                    $params[$k]=$v;
                }
                $client=new Client(env("MONGO_URI"));
                $database=$client->selectDatabase("review");
                $collection=$database->selectCollection("forms");
                $v=$collection->updateOne([
                    "uni_id"=>$uni_id
                ],['$set'=>$params]);
                $v=$v->getModifiedCount();
                $data['msg']='ok';
                $data['success']=true;
                $data['data']=$v;
                break;
            }
            case 'delete_form':{
                $uni_id=$request['uni_id']??null;
                if(empty($uni_id)){
                    throw new Exception('Error:no activity.form.uni_id');
                }
                $client=new Client(env("MONGO_URI"));
                $database=$client->selectDatabase("review");
                $collection=$database->selectCollection("forms");
                $v=$collection->deleteOne([
                    "uni_id"=>$uni_id
                ]);
                $v=$v->getDeletedCount();
                $data['msg']='ok';
                $data['success']=true;
                $data['data']=$v;
                break;
            }
            case 'vote_form':{
                $uni_id=$request['uni_id']??null;
                if(empty($uni_id)){
                    throw new Exception('Error:no activity.form.uni_id');
                }
                $client=new Client(env("MONGO_URI"));
                $database=$client->selectDatabase("review");
                $collection=$database->selectCollection("forms");
                $forms=$collection->findOne([
                    "uni_id"=>$uni_id
                ]);
                if(empty($forms)){
                    throw new Exception('Not Found:no activity.form.uni_id{'.$uni_id.'}');
                }
                $collection=$database->selectCollection("form_votes");
                $v=$collection->insertOne([
                    "user_id"=>$request['login_user_id']??1,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                    'created_at_str'=>date('Y-m-d H:i:s'),
                    'updated_at_str'=>date('Y-m-d H:i:s')
                ]);
                $id=$v->getInsertedId();
                $data['msg']='ok';
                $data['success']=true;
                $data['data']=$v;
                break;
            }
        }
        return $data;
    }
    public function actCreateForm(Request $request){
        $table="tbl_activity_forms";
        $xml="<?xml version='1.0' encoding='UTF-8'?>\r\n";
        $activity_id=$request->json('activity_id');
        $action=$request->json('action','vote');//vote review
        if(empty($activity_id))
         return response()->json(['success'=>false,'msg'=>'no activity']);
        $fields=$request->json('fields');
        if(empty($fields)){
         return response()->json(['success'=>false,'msg'=>'null fields']);
        }
        $xml.="<form action='{$action}' activity='{$activity_id}'>\r\n";
        $xml=ActivityFormModel::makeXml($action,$fields,$xml);
        $xml.="</form>";
        $doc=simplexml_load_string($xml);
        $filename="af_{$activity_id}_".time().'.xml';
        $filename=Xml2Object::FORMXML_SAVE_PATH.$filename;
        $v=$doc->saveXML($filename);
        list($model,$listener)=$this->requestModel($table,$request);
        if(empty($model)){
            return response()->json([
                'success'=>false
            ]);
        }
        $model['file']=$filename;
        $model['action']=$action;
        $s=$this->emitEvent($listener['action'],$model);
        return response()->json([
            'data'=>$model['id']??$model['uni_id']
        ]);
    }
    public function actSubmitForm(Request $request){
        $activity_id=$request->json('activity_id');
        $form_id=$request->json('form_id');
        $submiter_id=$request->json('submiter_id');
        $data=ActivityFormModel::parseSubmitForm($form_id,$request);
        if(empty($data)){
            return response()->json([
                'success'=>false
            ]);
        }
        $data['activity_id']=$activity_id;
        $data['form_id']=$form_id;
        $data['submiter_id']=$submiter_id;
        $data['created_at']=date('Y-m-d H:i:s');
        $data['updated_at']=date('Y-m-d H:i:s');
        $client=new Client("mongodb://mongo_ZeQxdC:mongo_5aWXeK@172.30.17.120:27017");
        $mongo=$client->selectDatabase("online_review");
        $coll=$mongo->selectCollection("activity_form_submit_list");
        $id=$coll->insertOne($data)->getInsertedId();
        return $id;
    }
    public function actReviewForm(Request $request){
        $activity_id=$request->json('activity_id');
        $form_id=$request->json('form_id');
        $object_id=$request->json('object_id');
        $user_id=$request->json('user_id');
        $user_ip=$request->getClientIp();
        $v=ActivityFormModel::shot([
            'activity_id'=>$activity_id,
            'form_id'=>$form_id,
            'object_id'=>$object_id,
            'user_id'=>$user_id,
            'user_ip'=>$user_ip,
        ]);
        if(empty($v)){
            return response()->json([
                'success'=>false
            ]);
        }else{
            return response()->json([
                'success'=>$v
            ]);
        }
    }
    public function actAnalysisForm(Request $request){
        $client=new Client("mongodb://mongo_ZeQxdC:mongo_5aWXeK@172.30.17.120:27017");
        $mongo=$client->selectDatabase("online_review");
        $coll=$mongo->selectCollection("activity_form_submit_list");
        $where=[];
        $activity_id=$request->json('activity_id');
        $form_id=$request->json('form_id');
        $submiter_id=$request->json('submiter_id');
        if(!empty($activity_id))
        $where["activity_id"]=$activity_id;
        if(!empty($form_id))
        $where["form_id"]=$form_id;
        if(!empty($submiter_id))
        $where["submiter_id"]=$submiter_id;
        $mWhere=[

        ];
        if(!empty($where))
        $mWhere[]=['$match'=>$where];
        $mWhere[]=['$group'=>[
            "_id"=>null,
            "cnt"=>['$count'=>(object)[]]
        ]];
        $mWhere[]=['$project'=>['cnt'=>1,'_id'=>0]];
        $cnt=$coll->aggregate(
            $mWhere
        );
        $data=[];
        foreach($cnt as $v){
            $data[]=$v;
        }
        return $data;
    }
    public function actDelete(Request $request){

    }
    public function actEdit(Request $request){
        $table="tbl_activitys";
        list($model,$listener)=$this->requestModel($table,$request,true);
        $s=$this->emitEvent($listener['action'],$model);
        return $s;
    }
    public function actQuery(Request $request){

    }
    public function actFlow(Request $request){

    }
    public function actView(Request $request){

    }
    public function actJoin(Request $request){

    }
    public function actQuit(Request $request){
        
    }
    public function actEnter(Request $request){

    }
    public function actExit(Request $request){

    }
    public function actUploadFile(Request $request){
        $data=[
            'code'=>-1,
            'msg'=>'fail',
            'data'=>null
        ];
        $exts=self::FILE_EXT_LIST;
        $file=$request->file('file');
        if($file&&$file->isValid()){
            $ext=strtoupper($file->getClientOriginalExtension());
            if(in_array($ext,$exts)){
                $path=$this->uploadFile($request);
                $data['data']=$path;
                $data['msg']='success';
                $data['code']=0;
            }else{
                $data['msg']='fail invalid ext('.$ext.')';
            }
        }else{
                $data['msg']='fail invalid file';
        }
        return $data;
    }
    private function uploadFile($request,$key='file',$path='public'){
            $path=$request->file($key)->store($path);
            return $path;
    }
}
